package com.zx.servicelearn.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.servicelearn.R;
import com.zx.servicelearn.aidl.IBookManager;
import com.zx.servicelearn.aidl.IOnNewBookArrivedListener;
import com.zx.servicelearn.model.Book;
import com.zx.servicelearn.service.IPCService1_Messenger;
import com.zx.servicelearn.service.IPCService2_AIDL;
import com.zx.servicelearn.utils.MyUtils;

import java.util.List;

/**
 * 模拟客户端进程
 */
public class IPCLearnActivity2 extends AppCompatActivity {
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {


            switch (msg.what) {
                case 1:
                    //收到了服务端返回的消息
                    Log.e("IPCLearnActivity2", "客户收到服务器消息：msg——————" + msg.getData().getString("reply"));
//                    textshow_tv.setText("客户收到服务器接口消息：msg——————" + msg.getData().getString("reply"));
                    break;
                case 2:
                    //服务器接口监听
                    Log.e("IPCLearnActivity2", "客户收到服务器接口消息：msg——————" + msg.obj);
//                    textshow_tv.setText("客户收到服务器接口消息：msg——————" + msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
    TextView textshow_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ipclearn2);
        textshow_tv = findViewById(R.id.textshow_tv);
        String processName = MyUtils.getProcessName(getApplicationContext(), android.os.Process.myPid());
        Log.e("IPCLearnActivity2", "onCreate-----processName：" + processName);


        Intent intent = new Intent(this, IPCService1_Messenger.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

        Intent intent2 = new Intent(this, IPCService2_AIDL.class);
        bindService(intent2, mServiceConnection2, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        unbindService(mServiceConnection);

        if (mIBookManager != null && mIBookManager.asBinder().isBinderAlive()) {
            Log.e("IPCLearnActivity2", "unregister listener：" + mIOnNewBookArrivedListener);
            try {
                mIBookManager.unregisterListener(mIOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mServiceConnection2);
        super.onDestroy();

    }

    Messenger messenger;
    ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("IPCLearnActivity2", "onServiceConnected----ComponentName：" + name);
            messenger = new Messenger(service);
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    IBookManager mIBookManager;
    ServiceConnection mServiceConnection2 = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIBookManager = IBookManager.Stub.asInterface(service);
            if (mIBookManager == null) {
                return;
            }
            try {
                mIBookManager.registerListener(mIOnNewBookArrivedListener);//注册监听

                service.linkToDeath(mDeathRecipient, 0);//注册死亡代理
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    /**
     * 服务端增加一条书，客户端会接受到监听消息，处理该消息
     */
    IOnNewBookArrivedListener mIOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub()

    {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            // TODO: 2018/1/19 测试直接跟新UI 如下异常
            //*** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
//            android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
//            textshow_tv.setText("客户收到服务器接口消息：msg——————" + book);


            mHandler.obtainMessage(2, book).sendToTarget();//主线程跟新UI 简化的发送一条消息，不需要new message或者obtain message

        }
    };

    /**
     * 向服务端发送一条消息，并接受其回复
     *
     * @param view
     */
    public void test1(View view) {
        Message msg = new Message();
        Bundle mBundle = new Bundle();
        mBundle.putString("msg", "客户端消息内容");
        msg.setData(mBundle);
        msg.replyTo = new Messenger(mHandler);//给服务端设置回复消息的messenger
        msg.what = 1;
        try {
            messenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向服务端添加一本书
     *
     * @param view
     */
    public void test2(View view) {
        try {
            if (mIBookManager == null) {//如果服务端在onBind中做了权限验证，可能会导致绑定失败,mIBookManager为空
                Toast.makeText(this, "绑定服务端失败！ mIBookManager is null", Toast.LENGTH_SHORT).show();
                return;
            }
            mIBookManager.addBook(new Book(1, "一本好书"));
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取服务端图书列表
     *
     * @param view
     */
    public void test3(View view) {
        try {
            if (mIBookManager == null) {//如果服务端在onBind中做了权限验证，可能会导致绑定失败,mIBookManager为空
                Toast.makeText(this, "绑定服务端失败！ mIBookManager is null", Toast.LENGTH_SHORT).show();
                return;
            }
            List<Book> mList = mIBookManager.getBookList();
            for (int i = 0; i < mList.size(); i++) {
                Log.e("IPCLearnActivity2", "书" + i + "：msg——————" + mList.get(i).toString());
                textshow_tv.setText("书" + i + "：msg——————" + mList.get(i).toString());

            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    // TODO: 2018/1/18 死亡代理
    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            //注意这里不能更新UI
            if (mIBookManager == null) {
                return;
            }
            mIBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
            mIBookManager = null;
            // TODO: 2018/1/18 这里重新绑定远程service
            Intent intent2 = new Intent(IPCLearnActivity2.this, IPCService2_AIDL.class);
            bindService(intent2, mServiceConnection2, Context.BIND_AUTO_CREATE);
        }
    };
}
